package com.xjk.http;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;


public class TSLClient {

    /**
     * 创建SSL请求客户端
     */
    public static CloseableHttpClient createTSLClient(){
        SSLContext sslContext = null;
        try{
            SSLContextBuilder builder = new SSLContextBuilder().useProtocol("TLSv1.2");
            sslContext = builder.loadTrustMaterial(null, new TrustStrategy(){

                @Override
                public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException{
                    // 通过所有证书
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier(){

                @Override
                public boolean verify(String hostname,SSLSession session){
                    // 不验证hostname
                    return true;
                }
            });
            // 如果异常了,创建普通的client
            return HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
        }catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e){
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }
}
